/*
 * Message.cpp
 *
 *  Created on: 24 mei 2013
 *      Author: maarten
 */

#include "Message.hpp"
#include <cstring>
#include <iostream>

Message::Message() {
	bufferLength = 0;
	bzero(buffer, BUFFERSIZE);
}

Message::Message(char aBuffer[], int length) :
		bufferLength(length) {
	bzero(buffer, BUFFERSIZE);
	if (length > 0) {
		memcpy(buffer, aBuffer, bufferLength);
	}
}

int Message::getHeader() {
	if (bufferLength > 0) {
		return (unsigned char) buffer[0];
	} else { //if read failed: return error code
		return bufferLength;
	}
}

char * Message::getBody() {
	return buffer + 2;
}

int Message::getBodyLength() {
	return bufferLength - 2;
}

std::vector<std::string> Message::parseBody() {
	std::vector<std::string> split;
	std::string message(buffer);

	while (message.length() != 0) {
		unsigned pos = message.find(SPLITTOKENC);
		if (pos != std::string::npos) {
			split.push_back(message.substr(0, pos));
			message.erase(0, pos + 1);
		}
	}
	return split;
}

void Message::setHeader(int aHeaderNr) {
	buffer[0] = (unsigned char) aHeaderNr;
	buffer[1] = SPLITTOKENC;
	bufferLength = 2;
}

void Message::addBody(std::string aBodyPart) {
	int start = bufferLength; //header + buffersize

	//add splittoken
	aBodyPart += SPLITTOKENC;

	bufferLength += aBodyPart.length();
	memcpy(buffer + start, aBodyPart.c_str(), aBodyPart.length());
}

void Message::addBody(char aBodyPart[], int length) {
	if (length > FILESPLIT) {
		length = FILESPLIT;
	}
	bufferLength = length + 2;
	memcpy(buffer + 2, aBodyPart, length);
}

char * Message::getCompleteMessage() {
	return buffer;
}

int Message::getCompleteMessageSize() {
	return bufferLength;
}

Message::~Message() {
}
